package main

import (
	"fmt"
	"github.com/robfig/cron"
	"time"
)

// http://code2life.top/2018/08/01/0028-go-snippets-1/
type MyScheduleJob struct {
}

func (MyScheduleJob) Next(time.Time) time.Time {
	fmt.Println("calc next")
	return time.Now().Add(10 * time.Second)
}
func (MyScheduleJob) Run() {
	fmt.Println("run job")
}

func main() {
	tz, _ := time.LoadLocation("Asia/Shanghai")
	c := cron.NewWithLocation(tz)
	// cron 表达式语法: 秒 分 时 天 月 周几
	// https://blog.csdn.net/weixin_40426638/article/details/78959972
	// Field name   | Mandatory? | Allowed values  | Allowed special characters
	// Seconds      | Yes        | 0-59            | * / , -
	// Minutes      | Yes        | 0-59            | * / , -
	// Hours        | Yes        | 0-23            | * / , -
	// Day of month | Yes        | 1-31            | * / , - ?
	// Month        | Yes        | 1-12 or JAN-DEC | * / , -
	// Day of week  | Yes        | 0-6 or SUN-SAT  | * / , - ?
	c.AddFunc("0 30 * * * *", func() {
		fmt.Println("Every hour on the half hour")
	})
	// @yearly (or @annually) = 0 0 0 1 1 *
	// @monthly = 0 0 0 1 * *
	// @weekly = 0 0 0 * * 0
	// @daily (or @midnight) = 0 0 0 * * *
	// @hourly = 0 0 * * * *
	c.AddFunc("@hourly", func() {
		fmt.Println("Every hour")
	})
	// @every Duration, 相当于time.NewTicker(time.ParseDuration("1h30m"))
	c.AddFunc("@every 1h30m", func() {
		fmt.Println("Every hour thirty")
	})
	c.Start()

	// 获取当前 CronTable 的详情
	entries := c.Entries()
	fmt.Printf("%v \n", entries[0].Next)
	fmt.Printf("%v \n", c.Location())

	// 自定义 ScheduleJob
	j := MyScheduleJob{}
	c.Schedule(j, j)
	fmt.Scanln()

}
